package com.yjw.demo.netty.bio_chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务端
 * 
 * @author yinjianwei
 * @date 2018/11/15
 */
public class Server {
    // 默认端口
    private static final int DEFAULT_SERVER_PORT = 8888;
    // 客户端列表
    private static List<Socket> clients = new ArrayList<>();
    // 服务端
    private static ServerSocket serverSocket = null;

    public static void start() {
        try {
            serverSocket = new ServerSocket(DEFAULT_SERVER_PORT);
            System.out.println("服务已启动，端口号：" + DEFAULT_SERVER_PORT);
            while (true) {
                Socket socket = serverSocket.accept();
                clients.add(socket);
                System.out.println("已连接客户端数量：" + clients.size());
                new Thread(new ServerHandler(socket, clients)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                serverSocket = null;
            }
        }
    }

    public static void main(String[] args) {
        start();
    }
}
